package com.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.dao.IFileMetaDao;
import com.dao.entity.FileMeta;
import com.service.IFileMetaService;
import com.service.aliyun.IOssService;
import com.utils.commons.Encoder;

@Service
@ConfigurationProperties(prefix="aliyun")
public class FileMetaServiceImpl implements IFileMetaService{
	
	private String repository;
	
	@Autowired
	private IFileMetaDao fileMetaDao;
	
	@Autowired
	private IOssService ossService;

	@Override
	public FileMeta saveFileMeta(FileMeta fileMeta) {
		return fileMetaDao.save(fileMeta);
	}

	@Override
	public List<Object> uplordFile(MultipartFile[] upfile, Long userId, Integer type) {
		List<Object> list = new ArrayList<Object>();
		for (int i = 0; i < upfile.length; i++) {
            //循环获取file数组中得文件
            MultipartFile file = upfile[i];
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            try {
            	InputStream filein = file.getInputStream();
            	String oldName = file.getOriginalFilename();
            	oldName = Encoder.toUTF8(oldName);
            	String suffix = oldName.substring(file.getOriginalFilename().lastIndexOf("."));
            	
            	fileName = fileName + suffix;
            	
            	StringBuffer path = new StringBuffer(repository);
            	FileMeta fileMeta = new FileMeta();
            	if(userId != null && type != null) {
            		path.append(type).append("/").append(userId).append("/");
            		fileMeta.setPersonid(userId);
            		fileMeta.setPersonType(type);
            	}
            	//上传文件
            	ossService.OSSUpload(path + fileName, filein);
            	
            	//返回json
            	Map<String,String> ossmap = ossService.fillOssAndCdnPath(path.toString(), fileName);
            	ossmap.put("fileName", oldName);
            	list.add(ossmap);
            	
            	fileMeta.setFileName(oldName);
            	fileMeta.setFileUrl(ossmap.get("ossUrl"));
            	this.saveFileMeta(fileMeta);
            } catch (Exception e){
                e.printStackTrace();
                Map<String, String> errorMap = new HashMap<String, String>();
                errorMap.put("ossUrl", "上传失败");
                errorMap.put("fileName", file.getOriginalFilename());
                list.add(errorMap);
            }
        }
		return list;
	}

	public String getRepository() {
		return repository;
	}

	public void setRepository(String repository) {
		this.repository = repository;
	}
	
}
